var category_type = null;
var progect_type = null;
var project_hivetype = null;
var project_state = null;
var voltage_type = null;
var bprojectapplicationall = null;//申请书
var bbudgetstandardall = null;//预算标准
var orgall = null;//所有人员
var userall = null;//所有单位
var userallmy = null;
var map = null;
// var type = null;
$(function () {
    $.when(getdatadictionary("category_type"),
        getdatadictionary("progect_type"),
        getdatadictionary("project_hivetype"),
        getdatadictionary("project_state"),
        getdatadictionary("voltage_type"),
        getbprojectapplicationall(),
        getbbudgetstandardall(),
        getorgall(),
        getuserall()).done(
        $("#jqGrid").jqGrid({
            url: baseURL + 'bss/apbase/list?state=isdelno&ourid=isok',
            datatype: "json",
            colModel: [
                {label: 'guid', name: 'guid', index: 'guid', width: 50, key: true, hidden: true},
                {label: '所属批次ID', name: 'bGuid', index: 'b_guid', width: 80, hidden: true},
                {
                    label: '业务类型', name: 'pBCategory', index: 'p_b_category', width: 80, hidden: true,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in category_type) {
                            if (cellvalue == category_type[d].dKey) return category_type[d].dValue;
                        }
                    }
                },
                {
                    hidden: true, label: '项目类别', name: 'pBType', index: 'p_b_type', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in progect_type) {
                            // type = cellvalue;

                            if (cellvalue == progect_type[d].dKey) return progect_type[d].dValue;
                        }
                    }
                },
                {
                    label: '储备状态', name: 'pBHive', index: 'p_b_hive', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in project_hivetype) {
                            if (cellvalue == project_hivetype[d].dKey) return project_hivetype[d].dValue;
                        }
                    }
                },
                {
                    label: '项目状态', name: 'pBState', index: 'p_b_state', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in project_state) {
                            if (cellvalue == project_state[d].dKey) return project_state[d].dValue;
                        }
                    }
                },
                {label: '项目名称', name: 'pBName', index: 'p_b_name', width: 200},
                {hidden: true, label: '项目地址', name: 'pBAddress', index: 'p_b_address', width: 80},
                {label: '项目经度', name: 'pBLongitude', index: 'p_b_longitude', width: 80, hidden: true},
                {label: '项目纬度', name: 'pBLatitude', index: 'p_b_latitude', width: 80, hidden: true},
                {
                    label: '项目单位', name: 'pBOrgid', index: 'p_b_orgid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {

                        for (d in orgall) {
                            if (cellvalue == orgall[d].deptId)
                                return orgall[d].name;
                        }
                    }
                },
                {
                    hidden: true, label: '所属申请书', name: 'aGuid', index: 'a_guid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {

                        for (d in bprojectapplicationall) {
                            if (cellvalue == bprojectapplicationall[d].guid) return bprojectapplicationall[d].pAName;
                        }
                    }
                },
                {
                    hidden: true, label: '所属预算标准', name: 'sGuid', index: 's_guid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        var names = "";

                        for (d in bbudgetstandardall) {
                            var ss = cellvalue.replace(/\"/g, "").replace("[", "").replace("]", "").split(",");

                            for (var i = 0; i < ss.length; i++) {
                                if (ss[i] == bbudgetstandardall[d].guid) {
                                    names += bbudgetstandardall[d].bSName + ",";
                                }
                            }


                        }
                        if (names.length > 0) {
                            names = names.substring(0, names.length - 1);
                        }
                        return names;
                    }
                },
                {
                    hidden: true, label: '最高电压等级', name: 'pBVoltage', index: 'p_b_voltage', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in voltage_type) {
                            if (cellvalue == voltage_type[d].dKey) return voltage_type[d].dValue;
                        }
                    }
                },
                {
                    label: '参与人', name: 'pBCollectid', index: 'p_b_collectid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        var names = "";


                        var ss = (cellvalue.replace(/\"/g, "").replace("[", "").replace("]", "") + "").split(",");
                        for (var i = 0; i < ss.length; i++) {

                            for (d in userall) {
                                if (ss[i] == userall[d].userId + "") {

                                    names += userall[d].username + ",";
                                }
                            }
                        }
                        if (names.length > 0) {
                            names = names.substring(0, names.length - 1);
                        }
                        return names;
                    }
                },

                {
                    label: '创建时间', name: 'pBAddtime', index: 'p_b_addtime', width: 80,
                    formatter: function (value, options, row) {
                        return value != null ? new Date(value).Format('yyyy-MM-dd hh:mm') : "";
                    }
                },
                {
                    label: '估算调整日期', name: 'pBChangetime', index: 'p_b_changetime', width: 80,
                    formatter: function (value, options, row) {
                        return value != null ? new Date(value).Format('yyyy-MM-dd hh:mm') : "";
                    }
                },
                {
                    label: '操作', name: '', width: 330, formatter: function (cellvalue, options, rowObject) {
                    // return  "<a  class='btn btn-primary' onclick='showother(\"" + rowObject.guid + "\",\"" + rowObject.pBType + "\")' >&nbsp;其它信息</a>"
                    //
                    //     +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showcj(\"" + rowObject.guid + "\",\"" + rowObject.pBLongitude + "\" ,\"" + rowObject.pBLatitude + "\")' >&nbsp;采集信息</a>"
                    //     +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='upbase(\"" + rowObject.guid + "\")' >&nbsp;设置批次</a>"
                    //     +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='upbasegd(\"" + rowObject.guid + "\" )' >&nbsp;项目归档</a>"

                    //  项目审核
                    var pst = "";
                    if (rowObject.pBState == "20") {
                        pst = "<a  class='btn btn-primary' onclick='projectAudit(\"" + rowObject.guid + "\" )' >&nbsp;项目审核</a>&nbsp;&nbsp;";
                    }


                    if (rowObject.pBType == 100 && rowObject.isDraw == "是") {

                        //  项目中只有一个台区时，才绘制横平竖直的单线图
                        var ser = "";
                        if (rowObject.totalRangeguid == 1)
                            ser = "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showDXT(\"" + rowObject.guid + "\",\"" + rowObject.pBName + "\")' >&nbsp;单线图&nbsp;&nbsp;&nbsp;</a>"


                        return "<a  class='btn btn-primary' onclick='showother(\"" + rowObject.guid + "\",\"" + rowObject.pBType + "\")' >&nbsp;其它信息</a>"

                            + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showcj(\"" + rowObject.guid + "\",\"" + rowObject.pBLongitude + "\" ,\"" + rowObject.pBLatitude + "\")' >&nbsp;采集信息</a>"
                            + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='upbase(\"" + rowObject.guid + "\")' >&nbsp;设置批次</a><br>"
                            + pst
                            // +  "<a  class='btn btn-primary' onclick='upbasegd(\"" + rowObject.guid + "\" )' >&nbsp;项目归档</a>"

                            + "<a  class='btn btn-primary' onclick='showDXF(\"" + rowObject.guid + "\",\"" + rowObject.pBName + "\")' >&nbsp;&nbsp;走向图&nbsp;&nbsp;&nbsp;</a>"
                            // + ser
                            // + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exportsssDXF(\"" + rowObject.guid + "\",\"" + rowObject.pBName + "\")' >&nbsp;导出DXF文件</a>"
                            + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exportAppFile(\"" + rowObject.guid + "\" )' >&nbsp;导出APP文件</a>"
                    } else {
                        return "<a  class='btn btn-primary' onclick='showother(\"" + rowObject.guid + "\",\"" + rowObject.pBType + "\")' >&nbsp;其它信息</a>"

                            + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showcj(\"" + rowObject.guid + "\",\"" + rowObject.pBLongitude + "\" ,\"" + rowObject.pBLatitude + "\")' >&nbsp;采集信息</a>"
                            + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='upbase(\"" + rowObject.guid + "\")' >&nbsp;设置批次</a>"
                            + pst
                            // +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='upbasegd(\"" + rowObject.guid + "\" )' >&nbsp;项目归档</a>"
                            + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exportAppFile(\"" + rowObject.guid + "\" )' >&nbsp;导出APP文件</a>"

                    }

                    // + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showgs(\"" + rowObject.guid + "\",\"" + rowObject.pBType + "\")' >&nbsp;估算</a>"
                    // +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exports(\"" + rowObject.guid + "\")' >&nbsp;导出</a>"

                }
                }

            ],
            viewrecords: true,
            height: 500,
            rowNum: 10,
            rowList: [10, 30, 50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth: true,
            multiselect: true,
            pager: "#jqGridPager",
            jsonReader: {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames: {
                page: "page",
                rows: "limit",
                order: "order"
            },
            gridComplete: function () {
                //隐藏grid底部滚动条
                $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            }
        })
    );


    // var a = $("#jqGrid").jqGrid('getCell',selIDs[i],"pBType");


    // map= new AMap.Map("container", {
    //      zoom: 18,
    //      resizeEnable: true,
    //     center: [106.949215,27.70325]
    //  });
    // map.on('click', function(e) {
    //      alert('您在[ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ]的位置设置成了项目地址！');
    //      vm.getdiwei(e.lnglat.getLng(),e.lnglat.getLat());
    //  });
    //  AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
    //
    //      var poiPicker = new PoiPicker({
    //          input: 'searchInput',
    //          placeSearchOptions: {
    //              map: map,
    //              pageSize: 10
    //          },
    //          searchResultsContainer: 'searchResults'
    //      });
    //
    //      poiPicker.on('poiPicked', function(poiResult) {
    //
    //          poiPicker.hideSearchResults();
    //
    //          var source = poiResult.source,
    //              poi = poiResult.item;
    //
    //          if (source !== 'search') {
    //
    //              //suggest来源的，同样调用搜索
    //              poiPicker.searchByKeyword(poi.name);
    //
    //          } else {
    //
    //              //console.log(poi);
    //          }
    //      });
    //
    //      poiPicker.onCityReady(function() {
    //          poiPicker.searchByKeyword('遵义');
    //      });
    //  });
});
function upbase(guid) {
    var title = "项目所属批次";
    var content = "apbaseupdate.html?guid=" + guid;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['80%', '40%'],
        content: content

    });
}


/**
 *  导出DXF文件
 *
 *  2018-10-19 10:49:09(旧版)
 */
function exportsssDXF(guid, pBName) {
    //
    var url = "csg/cpbase/exportDXF?pGuid=" + guid + "&pBName=" + pBName;
    location.href = baseURL + url;

    // $.post("/csg/cpbase/exportDXF", {
    //     pGuid: guid,
    //     pBName:pBName
    // }, "json");

}


function exports(guid) {

    location.href = baseURL + "bss/apbase/exports?guid=" + guid;

}


/**
 * 跳转到查看走向图页面
 *
 * @param guid -- 项目ID和项目名称
 * 2018-11-19 10:49:09(新版)
 */
function showDXF(guid, pBName) {

    // var url = "ashowdxfandexp.html?pGuid="+guid+"&pBName="+pBName ;
    // location.href = url;

    var title = "走向图";
    // var pGuid = vm.q.pGuid;
    var content ="ashowdxfandexp.html?pBName="+pBName+"&pGuid="+guid;
    layer.open({
        type: 2,

        title: false,
        area: ['95%', '95%'],
        content: content
    });
}


/**
 * 跳转到查看单线图页面
 *
 * @param guid -- 项目ID和项目名称
 * 2019-8-19 10:49:09(新版)
 */
function showDXT(guid, pBName) {

    // var url = "ashowdxfandexp.html?pGuid="+guid+"&pBName="+pBName ;
    // location.href = url;

    var title = "单线图";
    // var pGuid = vm.q.pGuid;
    var content = "ashowdxt.html?guid=" + guid + "&pBName=" + pBName;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['100%', '100%'],
        content: content
    });
}


function exportAppFile(guid) {
    var url = "fileLogin/exportProject?uuid=" + guid;
    location.href = baseURL + url;
}


/**
 *  项目审核
 * @param guid
 */
function projectAudit(guid) {

    layer.confirm('您是否要审核通过该项目？', {
        btn: ['审核不通过', '审核通过'] //按钮
    }, function () {
        var url = "bss/apbase/projectAudit";
        $.ajax({
            type: "POST",
            url: baseURL + url,
            data: {
                "guid": guid,
                "isPass": false
            },
            success: function (r) {
                layer.closeAll();
                vm.reload();
            }
        });

    }, function () {
        var url = "bss/apbase/projectAudit";
        $.ajax({
            type: "POST",
            url: baseURL + url,
            data: {
                "guid": guid,
                "isPass": true
            },
            success: function (r) {
                if (r.code === 0) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                } else {
                    alert(r.msg);
                }
            }
        });
    });

}


function upbasegd(guid) {

    layer.confirm('您是否要归档该项目？', {
        btn: ['取消', '归档'] //按钮
    }, function () {
        layer.closeAll();
    }, function () {
        var url = "bss/apbase/upbasegd";
        $.ajax({
            type: "POST",
            url: baseURL + url,
            contentType: "application/json",
            data: JSON.stringify(guid),
            success: function (r) {
                if (r.code === 0) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                } else {
                    alert(r.msg);
                }
            }
        });
    });

}


function showother(guid, ptype) {


    var title = "项目信息";
    var content = "apbaseothorall.html?guid=" + guid + "&ptype=" + ptype;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['95%', '95%'],
        content: content

    });
}
function showgs(guid, ptype) {


    var title = "项目估算";
    var content = "apbaseothorgs.html?guid=" + guid + "&ptype=" + ptype;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['95%', '95%'],
        content: content

    });
}

function showcj(guid, longitude, latitude) {
    var title = "采集信息";
    var content = "apbaseothorcj.html?guid=" + guid + "&longitude=" + longitude + "&latitude=" + latitude;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['95%', '95%'],
        content: content

    });
}

function showimg(longitude, latitude) {
    var title = " 地图查看";
    var content = "apbasemap.html?longitude=" + longitude + "&latitude=" + latitude;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['70%', '70%'],
        content: content

    });
}


function getdatadictionary(sss) {

    $.get(baseURL + "api/bdatadictionary/select?d_code=" + sss, function (r) {
        if (sss == "category_type") {
            category_type = r.returnlist;
        }
        if (sss == "progect_type") {
            progect_type = r.returnlist;
        }
        if (sss == "project_hivetype") {
            project_hivetype = r.returnlist;
        }
        if (sss == "project_state") {
            project_state = r.returnlist;
        }
        if (sss == "voltage_type") {
            voltage_type = r.returnlist;
        }
        vm.category_type = category_type;
        vm.progect_type = progect_type;
        vm.project_hivetype = project_hivetype;
        vm.project_state = project_state;
        vm.voltage_type = voltage_type;


    });
}


function getbprojectapplicationall() {
    $.get(baseURL + "api/bprojectapplication/select", function (r) {
        bprojectapplicationall = r.returnlist;
    });
}
function getbbudgetstandardall() {
    $.get(baseURL + "api/bbudgetstandard/select", function (r) {
        bbudgetstandardall = r.returnlist;
    });
}
function getorgall() {
    $.get(baseURL + "sys/dept/selectall", function (r) {
        orgall = r.returnlist;
    });
}
function getuserall() {
    $.get(baseURL + "sys/user/select", function (r) {
        userall = r.returnlist;
        userallmy = r.myuserlist;
    });
    vm.userall = userall;
    vm.userallmy = userallmy;
}


var vm = new Vue({
    el: '#rrapp',

    data: {
        q: {
            pBType: null,
            pBHive: null,
            pBName: null,
            pBState: null
        },
        bprojectapplicationall: bprojectapplicationall,
        bbudgetstandardall: bbudgetstandardall,
        orgall: orgall,
        userall: userall,
        userallmy: userallmy,

        showList: true,
        title: null,
        aPBase: {pBCollectid: []},
        status: ["是", "否"],

        category_type: category_type,
        progect_type: progect_type,
        project_hivetype: project_hivetype,
        project_state: project_state,
        voltage_type: voltage_type

    },
    methods: {
        query: function () {
            vm.reload();
        },
        gotosg: function (event) {
            var guid = getSelectedRow();
            if (guid == null) {
                return;
            }
            var url = "bss/apbase/gotosg";

            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(guid),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });

        },
        gotoys: function (event) {
            var guid = getSelectedRow();
            if (guid == null) {
                return;
            }
            var url = "bss/apbase/gotoys";

            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(guid),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });

        },

        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.aPBase = {pBCollectid: [], pBLongitude: null, pBLatitude: null},
                vm.category_type = category_type;
            vm.progect_type = progect_type;
            vm.project_hivetype = project_hivetype;
            vm.project_state = project_state;
            vm.voltage_type = voltage_type;
            vm.userall = userall;
            vm.userallmy = userallmy;
        },
        getdiwei: function (Longitude, Latitude) {
            vm.aPBase.pBLongitude = Longitude;
            vm.aPBase.pBLatitude = Latitude;
        },
        update: function (event) {
            var guid = getSelectedRow();
            if (guid == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.category_type = category_type;
            vm.progect_type = progect_type;
            vm.project_hivetype = project_hivetype;
            vm.project_state = project_state;
            vm.voltage_type = voltage_type;
            vm.userall = userall;
            vm.getInfo(guid);

        },
        saveOrUpdate: function (event) {
            var url = vm.aPBase.guid == null ? "bss/apbase/save" : "bss/apbase/update";

            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.aPBase),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var guids = getSelectedRows();
            if (guids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "bss/apbase/delete",
                    contentType: "application/json",
                    data: JSON.stringify(guids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (guid) {
            $.get(baseURL + "bss/apbase/info/" + guid, function (r) {
                vm.aPBase = r.aPBase;
                vm.aPBase.pBCollectid = r.aPBase.pBCollectid.replace(/\"/g, "").replace("[", "").replace("]", "").split(",");
                vm.userallmy = r.userallmy;
                var i = 0;
                var item = new Array();
                for (d in progect_type) {

                    if (progect_type[d].dKey == r.aPBase.pBType) {

                        item[i] = progect_type[d];
                        i++;
                    }
                }


                vm.progect_type = item;
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'pBType': vm.q.pBType,
                    'pBHive': vm.q.pBHive,
                    'pBName': vm.q.pBName,
                    'pBState': vm.q.pBState

                },
                page: page
            }).trigger("reloadGrid");
        }
    }
});